import React, { Component } from 'react';
import { Button,Dialog,Tab,Pagination,Icon,Menu,Overlay,Loading   } from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import CropperUpload from 'components/CropperUpload/index';
import { ajax } from 'utils/index';
export default class ImageSelector extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showPicDialog:false,
			showCropDialog:false,
			cropPreviewPic:"",
			overlayVisible:"none",
			showCatTree:false,
			imageList:[],
			itemList:[],
			curImagePage:1,
			totalImages:0,
			totalItems:0,
			imageCat:[],
			shopCat:[],
			curImageCatName:"所有图片",
			curShopCatName:"全部商品",
			loading:false,
			picType:"upload"
		};
		['getImages','resetSelectedImages','onCropOkay','onCropClose','onCropCancel',
		 'onDialogCancel','onDialogClose','imageFileUpload','imageFileUploadClick',
		 'onUploadSuccess','onUploadProgress','onUploadError',
		 'tabChange','getImageCat','getShopCat','getItemOnSell',
		 'imageCatClick','itemCatClick','onCropUsing','onLinkUsing'].map(fn => {
            this[fn] = this[fn].bind(this);
        });
	}
	
	seletedImages=[];
	curImageCat=0;
	curShopCat=0;
	imageFileUploadClick(){
		this.refs.imageFileUpload.click();
	}
	imageFileUpload(e){
		var _self=this;
		var file = e.target.files[0];
		var reader = new FileReader();
			reader.onload = function(u) {
				var image = new Image();
					image.onload=function(){
						// 请选择尺寸大于608x336的图片！
						var width = image.width;
						var height = image.height;
						var isAllow = width >= _self.props.minPicSize.width && height >= _self.props.minPicSize.height;
						if(isAllow){
							_self.setState({showCropDialog:true,cropPreviewPic:u.target.result});
						}else{
							_self.setState({"overlayVisible":"block"});
							setTimeout(function(){
								_self.setState({"overlayVisible":"none"})
							},2000);
						}
					};
					image.src= u.target.result;
			}
			if(typeof(file)=="object")
				reader.readAsDataURL(file)
	}
	onUploadSuccess(res){
		this.seletedImages.push(res.picture);
		if(typeof(this.props.onUploadSuccess)=="function")
			this.props.onUploadSuccess(res);
	}
	onUploadProgress(e){
		if(typeof(this.props.onUploadProgress)=="function")
			this.props.onUploadProgress(e);
	}
	onUploadError(err, res){
		if(typeof(this.props.onUploadError)=="function")
			this.props.onUploadError(err, res);
	}
	onCropCancel(){
		this.setState({"showCropDialog":false});
		if(typeof(this.props.onCropCancel)=="function")
			this.props.onCropCancel();
	}
	onCropClose(){
		this.setState({"showCropDialog":false});
		if(typeof(this.props.onCropClose)=="function")
			this.props.onCropClose();
		if(typeof(this.props.onClose)=="function")
			this.props.onClose();
	}
	onCropOkay(cropper){
		if(typeof(this.props.onCropOkay)=="function")
			this.props.onCropOkay(cropper);
	}
	onDialogCancel(){
		this.resetSelectedImages();
		if(typeof(this.props.onClose)=="function")
			this.props.onClose();
	}
	onDialogClose(){
		this.resetSelectedImages();
		this.setState({picType:"upload"});
		if(typeof(this.props.onClose)=="function")
			this.props.onClose();
	}
	onLinkUsing(){
		// onUploadSuccess
		if(this.seletedImages.length<=0){
			Dialog.alert({"content":"请选择图片！"})
			return;
		}
		this.onUploadSuccess({
			"picture":this.seletedImages[0]
		})
	}
	onCropUsing(){
		//选择图片对话框确认按钮
		let picUrl = "";
		switch(this.state.picType){
			case "upload":  //上传
				// console.log("上传文件");
			break;
			case "picApi":  //图片库
			case "itemApi":  //商品图片
				if(this.seletedImages.length>0){
					picUrl = this.seletedImages[0].picture_path;
					this.setState({showCropDialog:true,cropPreviewPic:this.seletedImages[0].picture_path});
				}else{
					Dialog.alert({"content":"请选择图片！"})
				}
			break;
		}
	}
	resetSelectedImages(){
		let imageList = this.state.imageList;
		imageList.map((img,index)=>{
			imageList[index].selected=false;
		});
		let itemList = this.state.itemList;
		itemList.map((img,index)=>{
			itemList[index].selected=false;
		});
		this.seletedImages.splice(0,this.seletedImages.length);
		this.setState({"imageList":imageList,"itemList":itemList,"showDialog":true});
	}
	getImages(page=1){
	  let _self=this;
	  let picture_category_id = this.curImageCat;
	  let success = (rsp, cmd, param)=>{
			if(!(rsp.pictures.picture instanceof Array)){
				rsp.pictures.picture = [rsp.pictures.picture];
			}
			let imageList = parseInt(rsp.totalResults)>0?
							rsp.pictures.picture:
							[];
				imageList.map((imgInList,index)=>{
					_self.seletedImages.map(imgSelected=>{
						if(imgInList.picture_id==imgSelected.picture_id){
							imageList[index].selected=true;
							return;
						}
					})
				})
			_self.setState({"imageList":imageList,"totalImages":parseInt(rsp.totalResults)});
	  }
	  if(window.QN){
		  window.QN.top.invoke( {
				cmd : 'taobao.picture.get',
				param : {"picture_category_id":picture_category_id,"page_size":_self.props.pageSize,"page_no":page},
				method:"post",
				error : function(msg, cmd, param) {
					// console.log(msg,param);
					Dialog.confirm({
						content:"读取图片数据出错，请重试。",
						title:'出错！'
					});
				},
				success : function(rsp, cmd, param) {
					success(rsp.picture_get_response, cmd, param);
				}
			} );
	  }else{
			ajax({
			  api: 'getImages',
			  method: 'GET',
			  data:{"picture_category_id":picture_category_id,"page_size":_self.props.pageSize,"page_no":page}
			},(json) => {
				  success(json);
			},(json) => {
				Dialog.confirm({
					content:"读取图片数据出错，请重试。",
					title:'出错！'
				});
				  
			});
	  }
	}
	imageCatClick(selectedKey){
		if(typeof(selectedKey)=="object"){
			this.setState({"curImageCatName":"所有图片"});
			this.curImageCat=0;
			this.getImages();
		}else if(selectedKey){
			this.state.imageCat.map(cat=>{
				if(cat.picture_category_id==selectedKey){
					this.setState({"curImageCatName":"所有>>"+cat.picture_category_name});
				}
			});
			this.curImageCat=(selectedKey);
			this.getImages();
		}
	}
	itemCatClick(selectedKey){
		if(typeof(selectedKey)=="object"){
			this.setState({"curShopCatName":"全部商品"});
			this.curShopCat=false;
			this.getItemOnSell();
		}else if(selectedKey){
			this.state.shopCat.map(cat=>{
				if(cat.cid==selectedKey){
					this.setState({"curShopCatName":"全部>>"+cat.name});
				}
			});
			this.curShopCat=selectedKey;
			this.getItemOnSell();
		}
	}
	getImageCat(parent_id=-1){
		let _self=this;
		if(window.QN){
			window.QN.top.invoke( {
				cmd : 'taobao.picture.category.get',
				param : {"parent_id":parent_id},
				method:"post",
				format:"xml",
				error : function(msg, cmd, param) {
					// console.log(msg);
					Dialog.confirm({
						content:"读取图片分类出错，请重试。",
						title:'出错！'
					});
				},
				success : function(rsp, cmd, param) {
					// console.log("遇到js最大数问题，等待api返回字符串类型id。");
					// console.log(rsp);
					// alert(rsp.picture_category_get_response.picture_categories.picture_category[1].picture_category_id);
					_self.setState({"imageCat":rsp.picture_category_get_response.picture_categories.picture_category});
				}
			} );
		}else{
			ajax({
			  api: 'getImageCatgory',
			  method: 'GET',
			  data:{"parent_id":parent_id}
			},(json) => {
				  //成功后
				  _self.setState({"imageCat":json.picture_categories.picture_category});
			},(json) => {
				  //失败后
				  //(json.code==53) W2超时
				Dialog.confirm({
					content:"读取图片分类出错，请重试。",
					title:'出错！'
				});
				  
			});
		}
	}
	getItemOnSell(page=1){
	  let _self=this;
	  let seller_cids = this.curShopCat;
	  let q = "";
	  let success = (rsp, cmd, param)=>{
			if(!(rsp.items.item instanceof Array)){
				rsp.items.item = [rsp.items.item];
			}
		  let items =
				rsp.total_results>0?
				rsp.items.item:
				[];
				items.map((imgInList,index)=>{
					_self.seletedImages.map(imgSelected=>{
						if(imgInList.num_iid==imgSelected.picture_id){
							items[index].selected=true;
							return;
						}
					})
				})
			_self.setState({"itemList":items,"totalItems":rsp.total_results});
	  }
		if(window.QN){
			  window.QN.top.invoke( {
					cmd : 'taobao.items.onsale.get',
					param : {"fields":"num_iid,title,pic_url","seller_cids":seller_cids,"q":q,"page_size":_self.props.pageSize,"page_no":page},
					method:"post",
					error : function(msg, cmd, param) {
						Dialog.confirm({
							content:"读取商品数据出错，请重试。",
							title:'出错！'
						});
					},
					success : function(rsp, cmd, param) {
						success(rsp.items_onsale_get_response, cmd, param);
					}
				} );
		}else{
			ajax({
			  api: 'getItemsOnsale',
			  method: 'GET',
			  data:{"fields":"num_iid,title,pic_url","seller_cids":seller_cids,"q":q,"page_size":_self.props.pageSize,"page_no":page}
			},(json) => {
				  //成功后
				  success(json);
			},(json) => {
				  //失败后
				  //(json.code==53) W2超时
				Dialog.confirm({
					content:"读取商品数据出错，请重试。",
					title:'出错！'
				});
				  
			});
		}
	}
	getShopCat(){
		let _self=this;
		if(window.QN){
			window.QN.top.invoke( {
				cmd : 'taobao.sellercats.list.get',
				param : {"nick":_self.props.userNick},
				method:"post",
				error : function(msg, cmd, param) {
					Dialog.confirm({
						content:"读取店铺分类出错，请重试。"+msg.sub_code,
						title:'出错！'
					});
				},
				success : function(rsp, cmd, param) {
					_self.setState({"shopCat":rsp.sellercats_list_get_response.seller_cats.seller_cat});
				}
			} );
		}else{
			ajax({
			  api: 'getSellerCats',
			  method: 'GET',
			  data:{"nick":_self.props.userNick},
			},(json) => {
				  //成功后
				  _self.setState({"shopCat":json.seller_cats.seller_cat});
			},(json) => {
				  //失败后
				  //(json.code==53) W2超时
				Dialog.confirm({
					content:"读取店铺分类出错，请重试。",
					title:'出错！'
				});
				  
			});
		}
	}
	tabChange(key) {
		if(key=="picApi" && this.state.imageList.length==0){
			this.getImages();
		}
		if(key=="picApi" && this.state.imageCat.length==0){
			this.getImageCat();
		}
		if(key=="itemApi" && this.state.shopCat.length==0){
			this.curImageCat=0;
			this.getShopCat();
		}
		if(key=="itemApi" && this.state.itemList.length==0){
			this.curShopCat=false;
			this.getItemOnSell();
		}
		this.setState({
			picType:key,
			showDialog: true
		});//强制更新对话框的位置
	}
	itemSelect(item_iid,pic_url){
		let itemList = this.state.itemList;
		let curItem = itemList.filter(c => c.num_iid === item_iid)[0];
		let index = itemList.indexOf(curItem);
		
		if(this.props.maxPic>1 && this.seletedImages.length>=this.props.maxPic && !curItem.selected){
			//如果最多超过1幅，则弹出提示框
			Dialog.alert({content:"最多只能选择"+this.props.maxPic+"幅图片！"});
			return;
		}
		
		if(this.props.maxPic==1 && !curItem.selected){
			//如果最多1副图，则取消之前的选择
			this.seletedImages.splice(0,this.seletedImages.length);
			itemList.map((img,index)=>{
				itemList[index].selected=false;
			});
		}
		
		itemList[index].selected = curItem.selected = !curItem.selected;
		
		if(curItem.selected){
			this.seletedImages.push({
				picture_id:item_iid,
				picture_path:pic_url
			});
		}else{
			// console.log(this.seletedImages);
			let selImg = this.seletedImages.filter(c => c.picture_id === item_iid)[0];
			let sIndex = this.seletedImages.indexOf(selImg);
			this.seletedImages.splice(sIndex,1);
		}
		// console.log(itemList);
		this.setState({"itemList":itemList});
	}
	imageSelect(picture_id,url){
		let imageList = this.state.imageList;
		let curImg = imageList.filter(c => c.picture_id === picture_id)[0];
		let pic_size = curImg.pixel.split("x");
		if(pic_size[0]<this.props.minPicSize.width || pic_size[1]<this.props.minPicSize.height){
			// Dialog.alert({content:"请选择尺寸大于608x336的图片！"});
			this.setState({"overlayVisible":"block"});
			var _self = this;
			setTimeout(function(){
				_self.setState({"overlayVisible":"none"})
				},2000);
			return;
		}else{
			this.setState({"overlayVisible":"none"});
		}
		let index = imageList.indexOf(curImg);
		
		if(this.props.maxPic>1 && this.seletedImages.length>=this.props.maxPic && !curImg.selected){
			//如果最多超过1幅，则弹出提示框
			Dialog.alert({content:"最多只能选择"+this.props.maxPic+"幅图片！"});
			return;
		}
		
		if(this.props.maxPic==1 && !curImg.selected){
			//如果最多1副图，则取消之前的选择
			this.seletedImages.splice(0,this.seletedImages.length);
			imageList.map((img,index)=>{
				imageList[index].selected=false;
			});
		}
		
		imageList[index].selected = curImg.selected = !curImg.selected;
		
		if(curImg.selected){
			this.seletedImages.push(curImg);
		}else{
			let selImg = this.seletedImages.filter(c => c.picture_id === picture_id)[0];
			let sIndex = this.seletedImages.indexOf(selImg);
			this.seletedImages.splice(sIndex,1);
		}
		this.setState({"imageList":imageList});
	}
	render() {
		let imageList = this.state.imageList;
		let itemList = this.state.itemList;
		let extraTabButton = "";
		let dialogFooter = "";
		if(this.state.picType=="upload"){
			dialogFooter = <div><Button type="normal" onClick={this.onDialogClose}>取消</Button></div>;
		}else{
			if(this.props.onlyCrop){
				dialogFooter = <div>
								<Button type="primary" onClick={this.onCropUsing}>裁切引用</Button> &nbsp;&nbsp;
								<Button type="normal" onClick={this.onDialogClose}>取消</Button>
							  </div>
			}else{
				dialogFooter = <div>
								<Button type="primary" onClick={this.onLinkUsing}>直接引用</Button> &nbsp;&nbsp;
								<Button type="primary" onClick={this.onCropUsing}>裁切引用</Button> &nbsp;&nbsp;
								<Button type="normal" onClick={this.onDialogClose}>取消</Button>
							  </div>
			}
		}
		switch(this.state.picType){
			case "picApi":
				const imageLoop = (data) => data.map((item) => {
					return <Menu.Item key={item.picture_category_id}>{item.picture_category_name}</Menu.Item>;
				});
				const subMenu = imageLoop(this.state.imageCat);
				const picMenu = (
					<Menu onClick={this.imageCatClick} style={{height:"390px",overflowX:"auto"}}>
						{subMenu}
					</Menu>
				);
				extraTabButton = <Button.Split onClick={this.imageCatClick} menu={picMenu} type="normal" size="small">{this.state.curImageCatName}</Button.Split>;
			break;
			case "itemApi":
				const shopLoop = (data) => data.map((item) => {
					return <Menu.Item key={item.cid}>{item.name}</Menu.Item>;
				});
				const subShopMenu = shopLoop(this.state.shopCat);
				const shopMenu = (
					<Menu onClick={this.itemCatClick} style={{height:"390px",overflowX:"auto"}}>
						{subShopMenu}
					</Menu>
				);
				extraTabButton = <Button.Split onClick={this.itemCatClick} menu={shopMenu} type="normal" size="small">{this.state.curShopCatName}</Button.Split>;
			break;
		} 
		return(
			<Dialog visible = {this.props.showPicDialog}
					shouldUpdatePosition = {true}
					style = {this.props.selectorStyle}
					title = "请选择图片"
					footer = {dialogFooter}
					onClose = {this.onDialogClose}
					minMargin = {40}>
				<CropperUpload
					name="userfile" //与服务器端对应的文件名，本版只支持一次上传一个文件
					showCropDialog={this.state.showCropDialog}
					cropPreviewPic={this.state.cropPreviewPic}
					onUploadSuccess={this.onUploadSuccess}
					onUploadProgress={this.onUploadProgress}
					onUploadError={this.onUploadError}
					onCropOkay={this.onCropOkay}
					onCropCancel={this.onCropCancel}
					onCropClose={this.onCropClose}
					aspectRatio={parseFloat(this.props.aspectRatio)}
					dialogStyle={this.props.cropperDialogStyle}
					copperStyle={this.props.copperStyle}
					uploadServer={this.props.uploadServer}
					previewList={this.props.previewList}>
				</CropperUpload>
				<div key="notice" 
					 style={{position:"absolute",top:"88px",width:"1058px",zIndex:99,display:this.state.overlayVisible}} 
					 className="next-notice next-notice-warning next-notice-standalone next-notice-medium next-notice-title-content fadeInDown">
					 <i className="next-icon next-icon-warning next-icon-medium next-notice-symbol"></i>
					 <div className="next-notice-title">请选择尺寸大于{this.props.minPicSize.width}x{this.props.minPicSize.height}的图片！</div>
				</div>
				<Tab onChange={this.tabChange} defaultActiveKey="upload" size="small" tabBarExtraContent={extraTabButton}>
					<Tab.TabPane tab="上传图片" key="upload" contentStyle={{width: '600px',height:"100px"}}>
						<Row type="wrap" justify="center" style={{marginTop:"50px"}}>
							<input type="file" ref="imageFileUpload" onChange={this.imageFileUpload} style={{display:"none"}}/>
							<Button type="primary" onClick={this.imageFileUploadClick} style={{margin: 0}}>上传图片</Button>
						</Row>
						<Row type="wrap" justify="center" style={{minHeight:"120px"}}>
							<div style={{width:"600px",maxWidth:"none",position:"relative",marginTop:"20px",color:"#666666"}} className=" next-balloon next-balloon-normal  next-balloon-medium next-balloon-top">
								提示：文件大小请在<strong>3M</strong>以内,<br />
								移动端尺寸为<strong>宽度480-1242之间，高度小于等于1546</strong>，
								仅支持<strong>JPG、PNG、GIF</strong>格式；<br />
								建议上传无线详情图片宽度<strong>750px</strong>以上，效果更佳
							</div>
						</Row>
					</Tab.TabPane>
					<Tab.TabPane tab="选择图片库图片" key="picApi">
						<Row type="wrap" style={{minHeight:"120px"}}>
						{imageList.map((img,index) => {
						  const selected = img.selected?<Icon type="success-filling" style={{position:"absolute",bottom:0,right:0,color:"red"}} />:"";
						  return (
							  <Col fixedSpan="6" style={{position:"relative",textAlign:"center",border: "2px solid #f1f1f1",marginRight:"5px",marginBottom:"5px",padding:"2px"}} key={index} onClick={this.imageSelect.bind(this,img.picture_id,img.picture_path)}>
								<div style={{height:"100px"}}><img src={img.picture_path+"_100x100"} /></div>
								<span title="230" className="next-badge next-badge-not-a-wrapper">
								  <sup className="next-badge-scroll-number next-badge-count" style={{backgroundColor: "rgb(135, 208, 104)"}}>
								  {img.pixel}
								  </sup>
								</span>
								{selected}
							  </Col>
						  );
						})}
						</Row>
						 <Row>
							<Pagination style={{margin:"0 auto"}} defaultCurrent={1}  pageSize={this.props.pageSize} total={parseInt(this.state.totalImages)} onChange={this.getImages} />
						 </Row>
					</Tab.TabPane>
					<Tab.TabPane tab="选择商品图片" key="itemApi">
							<Row type="wrap" style={{minHeight:"120px"}}>
								{itemList.map((itm,index) => {
								  const selected = itm.selected?<Icon type="success-filling" style={{position:"absolute",top:0,right:0,color:"red"}} />:"";
								  return (
									<Col fixedSpan="6" style={{position:"relative",textAlign:"center",border: "2px solid #f1f1f1",marginRight:"5px",marginBottom:"5px",padding:"2px"}} key={itm.num_iid} onClick={this.itemSelect.bind(this,itm.num_iid,itm.pic_url)}>
										<img  src={itm.pic_url+"_100x100"} />
										{selected}
										<p style={{fontSize:"12px"}} className="next-badge-scroll-number next-badge-count">
										  {itm.title}
										</p>
									</Col>
								  );
								})}
							</Row>
						<Row>
							<Pagination style={{margin:"0 auto"}} defaultCurrent={1}  pageSize={this.props.pageSize} total={parseInt(this.state.totalItems)} onChange={this.getItemOnSell} />
						</Row>
					</Tab.TabPane>
				</Tab>
			</Dialog>
		);
	}
}
